<template>
	<view class="container">
		<!-- 头部导航 -->
		<view class="header">
			<view class="header-left" :style="{ marginTop: safeTop + 'px' }">
				<image v-if="userInfo.identity != 2" @click="goToProfile" src="/static/base/index/store.png"
					class="menu-icon" mode="aspectFit" />
			</view>
			<view class="header-title" :style="{ marginTop: safeTop + 'px' }">发布作品</view>
			<view class="header-right"></view>
		</view>

		<scroll-view scroll-y class="content">
			<view :style="{ height: contentTop + 'px' }"></view>
			<!-- 输入区域 -->
			<view class="input-section">
				<!-- 第二行：取消 + 发布按钮 -->
				<view class="header-row-2">
					<!-- <text class="cancel-btn" @click="goBack">取消</text> -->
					<text class="publish-btn" :class="{ disabled: !canPublish }" @click="publishWork">发布</text>
				</view>

				<!-- 标题输入 -->
				<input v-model="workTitle" class="title-input" placeholder="请输入作品标题" maxlength="50"
					@input="onTitleInput" />

				<!-- 内容输入 -->
				<textarea v-model="workContent" class="content-input" placeholder="这一刻想说的话... ..." maxlength="500"
					@input="onContentInput" />

				<!-- 图片上传区域 -->
				<view class="image-section">
					<view class="image-upload-area">
						<view class="add-image-btn" @click="chooseImage" v-if="selectedImages.length === 0">
							<image src="/static/base/public/image.svg" class="add-icon" mode="aspectFit" />
							<text class="add-text">添加照片</text>
						</view>

						<view class="selected-images" v-if="selectedImages.length > 0">
							<view v-for="(image, index) in selectedImages" :key="index" class="image-item">
								<image :src="image.url" class="uploaded-image" mode="aspectFill" />
								<view class="delete-btn" @click="removeImage(index)">
									<text class="delete-text">×</text>
								</view>
							</view>
							<view v-if="selectedImages.length < 9" class="add-more-btn" @click="chooseImage">
								<text class="add-more-text">+</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 热门推荐区域 -->
			<view class="recommend-section">
				<view class="section-title">
					<text class="title-text">- - - 热门推荐 - - -</text>
				</view>

				<view v-if="hotWorks.length > 0" class="works-list">
					<view v-for="(work, index) in hotWorks" :key="index" class="work-item"
						@click="goToWorkDetail(work.id)">
						<image :src="work.avatar" class="user-avatar" mode="aspectFill" />
						<view class="work-info">
							<view class="work-header" style="display: flex;justify-content: space-between;">
								<view class="username">
									{{ work.nickname }}
									<text v-if="work.identity==2" class="identity-title">设计师</text>
									<text v-if="work.identity!=2 & work.work_level == 0">创作者</text>
									<!-- <image v-if="work.identity != 2 & work.work_level > 0" class="mvp-img"
									 :src="'/static/base/user-center/level/' + work.levelImg"> -->
								</view>
								<view class="work-add_time">{{ work.add_time }}</view>
							</view>
							<text class="work-content">{{ work.title }}</text>
							<text class="work-content">{{ work.content }}</text>

							<view v-if="work.images && work.images.length > 0" class="work-images">
								<image @tap.native.stop="previewImages(work.images)"
									v-for="(img, imgIndex) in work.images" :key="imgIndex" :src="img" class="work-thumb"
									mode="aspectFill" />
							</view>
							<view v-else class="work-images">
								<!-- <image src="/static/base/empty.png" class="work-thumb" mode="aspectFill" /> -->
								<image :src="imgHost + '/statics/images/no-thing.png'" class="work-thumb"
									mode="aspectFill"></image>
							</view>

						</view>
					</view>
				</view>

				<view v-else-if="!isLogin" class="empty-tips">
					<text style="color: #ff914f;" @click="goToLogin">点击登录</text></navigator> 查看热门推荐作品哦~
				</view>
				<view v-else class="empty-tips">暂无热门推荐作品哦~</view>

				<view style="height: 121.45rpx;"></view>
			</view>
		</scroll-view>

		<TableBar :current="-1" :messagecount="messagecount" />
	</view>
</template>

<script>
	import TableBar from '@/components/base/table-bar/Index.vue'
	import {
		getUnreadMessage
	} from '@/api/base/message.js'
	import {
		publishCreativeWork,
	} from '@/api/base/publish.js'

	import {
		USER_INFO,
		UID,
		LOGIN_STATUS
	} from '@/config/cache';
	import Cache from '@/utils/cache';
	import {
		getBaseUserInfo
	} from '@/api/base/user-center'; // 注意：新接口无参数
	import {
		getWorkList
	} from '@/api/base/index.js'
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	import {
		mapGetters
	} from 'vuex';

	export default {
		components: {
			TableBar
		},
		data() {
			return {
				messagecount: 0,
				imgHost: HTTP_REQUEST_URL,
				userInfo: {},
				safeTop: 0,
				contentTop: 0,
				workTitle: '',
				workContent: '',
				selectedImages: [],
				hotWorks: []
			}
		},
		computed: {
			...mapGetters(['isLogin']),
			canPublish() {
				const hasTitle = this.workTitle.trim().length > 0
				const hasWorkContent = this.workContent.trim().length > 0

				// const hasContentOrImage = this.workContent.trim().length > 0 && this.selectedImages.length > 0
				return hasTitle && hasWorkContent
			}
		},
		onLoad() {
			const {
				barTop
			} = this.$util.getWXStatusHeight()
			this.safeTop = barTop + 2
			this.contentTop = barTop + 36

			if (this.isLogin) {
				this.initData();
			}

		},
		onShow() {
			if (this.isLogin) {
				this.initMessage();
			}
		},
		methods: {
			initData() {
				getWorkList('', 1, 10, 0, 1).then(res => {
					if (res.status === 200) {
						this.hotWorks = (res.data.list || []).map(item => ({
							...item,
							levelImg: this.levelImg(item.work_level)
						}));
					} else {
						console.log('获取数据失败！')
					}
				}).catch(err => {
					console.log(err)
				})
				this.getUserInfo(); // 调用无参接口
			},
			initMessage() {
				getUnreadMessage().then(res => {
					if (res.status === 200) {
						this.messagecount = res.data.like + res.data.comment
					} else(err => {
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						})
						console.log('获取数据失败', err);
					})
				}).catch(err => {
					console.log('获取数据失败', err);
				})
			},
			levelImg(work_level) {
				const map = ['', '1.png', '2.png', '3.png', '4.png', '5.png'];
				return map[work_level];
			},
			getUserInfo() {
				// 新接口无需传参
				getBaseUserInfo().then(res => {
					const cacheUserInfo = JSON.parse(Cache.get(USER_INFO));
					if (res.status === 200 && res.data) {
						// 将后端返回字段赋值给 userInfo
						this.userInfo = {
							...this.userInfo,
							...res.data,
							// 可选：显式转换数值字段（虽后端返回数字，但保险起见）
							phoneNumber: res.data.phone,
							follow_count: res.data.follow_count || 0,
							fans_count: res.data.fans_count || 0,
							comment_count: res.data.comment_count || 0,
							work_like_count: res.data.work_like_count || 0,
							share_count: res.data.share_count || 0,
							income: res.data.income || '0.00'
						};
					}
				}).catch(err => {
					console.log('获取用户信息失败', err);
					// 可选：失败时重置或提示
				});
			},
			previewImages(imgs) {
				console.log(imgs)
				// 预览图片
				uni.previewImage({
					urls: imgs
				});
			},
			goToProfile() {
				uni.navigateTo({
					url: '/pages/index/index'
				})
			},
			goBack() {
				if (this.workTitle.trim() || this.workContent.trim() || this.selectedImages.length > 0) {
					uni.showModal({
						title: '提示',
						content: '确定要放弃编辑吗？',
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack()
							}
						}
					})
				} else {
					uni.navigateBack()
				}
			},
			onTitleInput(e) {
				this.workTitle = e.detail.value
			},
			onContentInput(e) {
				this.workContent = e.detail.value
			},
			chooseImage() {
				const remainCount = 9 - this.selectedImages.length
				// #ifdef MP-WEIXIN
				uni.getSetting({
					success: () => this._chooseImage(remainCount),
					fail: () => this._chooseImage(remainCount)
				})
				// #endif
				// #ifndef MP-WEIXIN
				this._chooseImage(remainCount)
				// #endif
			},
			_chooseImage(count) {
				uni.chooseImage({
					count,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						res.tempFilePaths.forEach((path) => {
							this.selectedImages.push({
								url: path,
								tempPath: path
							})
						})
					},
					fail: (err) => {
						console.error('chooseImage fail:', err)
						if (err.errMsg && /auth deny|permission/i.test(err.errMsg)) {
							uni.showToast({
								title: '请允许访问相册',
								icon: 'none'
							})
						}
					}
				})
			},
			removeImage(index) {
				this.selectedImages.splice(index, 1)
			},
			async publishWork() {
				if (!this.canPublish) {
					uni.showToast({
						title: '请填写标题，并输入内容或添加图片',
						icon: 'none',
						duration: 2000
					})
					return
				}

				uni.showLoading({
					title: '发布中...'
				})

				try {
					// 1. 上传图片
					const uploadedImageUrls = []
					for (const img of this.selectedImages) {
						const url = await new Promise((resolve, reject) => {
							this.$util.uploadImgs(
								'upload/image', //确保这是正确的接口路径
								img.tempPath,
								(res) => {
									if (res.status === 200) {
										resolve(res.data?.url || res.url || '')
									} else {
										reject(new Error(res.msg || '上传失败'))
									}
								},
								(err) => {
									reject(new Error(err.msg || '上传出错'))
								}
							)
						})
						uploadedImageUrls.push(url)
					}

					// 2. 发布作品
					const formData = {
						title: this.workTitle.trim(),
						content: this.workContent.trim(),
						images: JSON.stringify(uploadedImageUrls)
					}

					const res = await publishCreativeWork(formData)
					if (res.status === 200) {
						uni.showToast({
							duration: 2000,
							title: '已发布，请等待审核',
							icon: 'success'
						})
						setTimeout(function() {
							uni.navigateTo({
								url: '/pages/sub_base/my-created/index'
							})
						})
						// 关键：发布成功后初始化表单（不清除页面）
						this.resetForm()

						// 可选：延迟 1.5 秒再清空提示（用户体验更好）
						// setTimeout(() => { this.resetForm() }, 1500)
					} else {
						throw new Error(res.msg || '发布失败')
					}
				} catch (error) {
					uni.showToast({
						title: error,
						icon: 'none'
					})
					console.error('发布失败:', error)
				} finally {
					uni.hideLoading()
				}
			},
			resetForm() {
				this.workTitle = ''
				this.workContent = ''
				this.selectedImages = []
			},
			goToWorkDetail(id) {
				uni.navigateTo({
					url: `/pages/sub_base/creative-detail/index?id=${id}`
				})
			}
		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
	}

	/* 头部样式 */
	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		/* height: 44px; */
		background-color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 27.76rpx;
		z-index: 100;
	}

	.header-left {
		width: 88rpx;
		height: 76.14rpx;
		/* margin-left: -10.41rpx; */
		margin-top: 12.145rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.header-right {
		width: 76.14rpx;
	}

	.header-title {
		font-size: 31.23rpx;
		font-weight: 600;
		color: #333333;
	}

	.header-right {
		width: 104.1rpx;
	}

	/* 新增标题输入框样式 */
	.title-input {
		width: 100%;
		height: 70rpx;
		font-size: 32rpx;
		color: #333333;
		border: none;
		outline: none;
		border-bottom: 1px solid #eee;
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
	}



	.menu-icon {
		width: 45rpx;
		height: 45rpx;
	}

	.menu-btn {
		width: 41.64rpx;
		height: 41.64rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.menu-line {
		width: 100%;
		height: 3.47rpx;
		background-color: #333333;
		border-radius: 1.735rpx;
	}

	.more-btn {
		font-size: 34.7rpx;
		color: #666666;
		width: 41.64rpx;
		text-align: center;
	}

	.header-row-2 {
		display: flex;
		align-items: center;
		justify-content: space-between;
		/* margin-top: 17.35rpx; */
		margin-bottom: 22rpx;
	}

	.cancel-btn {
		font-size: 34rpx;
		color: #000000;
	}

	.publish-btn {
		background-color: #F19060;
		color: #ffffff;
		padding: 18rpx 66rpx;
		border-radius: 40rpx;
		font-size: 27rpx;
		/* font-weight: 300; */
		margin-left: auto;
	}

	/* 禁用发布按钮样式 */
	.publish-btn.disabled {
		/* background-color: #F19060 !important; */
		/* color: #999 !important; */
	}

	/* 内容区域 */
	.content {
		/* padding-top: calc(var(--status-bar-height) + 40px); */
		height: calc(100vh - 100rpx);
	}

	/* 输入区域 */
	.input-section {
		background-color: #ffffff;
		padding: 20rpx 32rpx;
		border-top: 6rpx solid #f1f1f1;
	}

	.content-input {
		margin-top: 36rpx;
		width: 100%;
		min-height: 138.8rpx;
		font-size: 25rpx;
		color: #333333;
		line-height: 1.5;
		border: none;
		outline: none;
	}

	/* 图片上传区域 */
	.image-section {
		background-color: #ffffff;
		border-radius: 13.88rpx;
	}

	.image-upload-area {
		min-height: 208.2rpx;
	}

	.add-image-btn {
		width: 173.5rpx;
		height: 173.5rpx;
		border: 3.47rpx dashed #dddddd;
		border-radius: 13.88rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #fafafa;
	}

	.add-icon {
		width: 55.52rpx;
		height: 55.52rpx;
		margin-bottom: 13.88rpx;
	}

	.add-text {
		font-size: 20.82rpx;
		color: #5a5a5a;
	}

	.selected-images {
		display: flex;
		flex-wrap: wrap;
		gap: 13.88rpx;
	}

	.image-item {
		position: relative;
		width: 173.5rpx;
		height: 173.5rpx;
		border-radius: 13.88rpx;
		overflow: hidden;
	}

	.uploaded-image {
		width: 100%;
		height: 100%;
	}

	.delete-btn {
		position: absolute;
		top: 6.94rpx;
		right: 6.94rpx;
		width: 34.7rpx;
		height: 34.7rpx;
		background-color: rgba(0, 0, 0, 0.6);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.delete-text {
		font-size: 24.29rpx;
		color: #ffffff;
		line-height: 1;
	}

	.add-more-btn {
		width: 173.5rpx;
		height: 173.5rpx;
		border: 3.47rpx dashed #dddddd;
		border-radius: 13.88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fafafa;
	}

	.add-more-text {
		font-size: 55.52rpx;
		color: #999999;
	}

	/* 热门推荐区域 */
	.recommend-section {
		background-color: #F2F8FC;
		padding: 20.82rpx;
	}

	.section-title {
		text-align: center;
		margin-bottom: 27.76rpx;
	}

	.title-text {
		font-size: 27.76rpx;
		font-weight: 600;
		color: #333333;
	}

	.works-list {
		margin-top: -26.025rpx;
	}

	.work-item {
		display: flex;
		align-items: flex-start;
		padding: 27.76rpx 0;
		border-bottom: 1.735rpx solid #f5f5f5;
	}

	.work-item:last-child {
		border-bottom: none;
	}

	.user-avatar {
		width: 69.4rpx;
		height: 69.4rpx;
		border-radius: 50%;
		margin-right: 20.82rpx;
		flex-shrink: 0;
	}

	.work-info {
		flex: 1;
		overflow-x: auto;
		/* 允许横向滚动 */
		min-width: 0;
		/* 防止 flex 布局下子元素撑开父容器 */
	}

	.work-header {
		margin-bottom: 6.94rpx;
	}

	.username {
		font-size: 36rpx;
		font-weight: 500;
		color: #858585;
	}

	.work-content {
		font-size: 20.82rpx;
		color: #4f4f4f;
		line-height: 1.4;
		margin-bottom: 4rpx;
		display: -webkit-box;
		/* 必须设置为 -webkit-box */
		-webkit-box-orient: vertical;
		/* 设置子元素排列方式为垂直 */
		-webkit-line-clamp: 2;
		/* 限制显示 2 行 */
		overflow: hidden;
		/* 超出隐藏 */
		text-overflow: ellipsis;
		/* 配合使用，虽然多行时主要靠 -webkit-line-clamp */
	}

	.work-images {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		/* 关键：禁止换行 */
		gap: 6.94rpx;
		margin-bottom: 13.88rpx;
		overflow-x: auto;
		padding: 6.94rpx 0;
		scrollbar-width: none;
		-ms-overflow-style: none;
		-webkit-overflow-scrolling: touch;
	}

	.work-images::-webkit-scrollbar {
		display: none;
	}

	.work-thumb {
		width: 156.15rpx;
		height: 156.15rpx;
		border-radius: 6.94rpx;
		flex-shrink: 0;
	}

	.more-images {
		width: 104.1rpx;
		height: 104.1rpx;
		border-radius: 6.94rpx;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.more-text {
		font-size: 20.82rpx;
		color: #ffffff;
	}

	.work-add_time {
		float: right;
		font-size: 20.82rpx;
		color: #999999;
	}

	.identity-title {
		background-color: #E6F2F9;
		color: #84BDE3;
		padding: 2rpx 12rpx;
		border-radius: 12rpx;
		margin-left: 28rpx;
	}

	.mvp-img {
		height: 38rpx;
		/* width: 38rpx; */
		width: 138rpx;
		margin-left: 20rpx;
	}
	
	.empty-tips {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 100rpx 0;
	}
</style>